package com.ecp.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Encoding {

	public Encoding() {
	}

	public static String native2ascii(final String nativeStr) {
		StringBuffer ret = new StringBuffer();
		if (nativeStr == null) {
			return null;
		}
		int maxLoop = nativeStr.length();
		for (int i = 0; i < maxLoop; i++) {
			char character = nativeStr.charAt(i);
			final int n127 = 127;
			final int n4 = 4;
			if (character <= n127) {
				ret.append(character);
			} else {
				ret.append("\\u");
				String hexStr = Integer.toHexString(character);
				int zeroCount = n4 - hexStr.length();
				for (int j = 0; j < zeroCount; j++) {
					ret.append('0');
				}
				ret.append(hexStr);
			}
		}
		return ret.toString();
	}

	public static String ascii2native(final String asciiStr) {
		if (asciiStr == null) {
			return null;
		}

		StringBuffer retBuf = new StringBuffer();
		int maxLoop = asciiStr.length();
		for (int i = 0; i < maxLoop; i++) {
			if (asciiStr.charAt(i) == '\\') {
				final int n5 = 5;
				final int n6 = 6;
				final int n16 = 16;
				if (i < maxLoop - n5
						&& (asciiStr.charAt(i + 1) == 'u' || asciiStr
								.charAt(i + 1) == 'U')) {
					try {
						retBuf.append((char) Integer.parseInt(asciiStr
								.substring(i + 2, i + n6), n16));
						i += n5;
					} catch (NumberFormatException e) {
						retBuf.append(asciiStr.charAt(i));
					}
				} else {
					retBuf.append(asciiStr.charAt(i));
				}
			} else {
				retBuf.append(asciiStr.charAt(i));
			}
		}

		return retBuf.toString();
	}

	public static String native2asciiWithoutComment(final String fileName)
			throws IOException {
		StringBuffer buf = new StringBuffer();
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		boolean continueFlg = false;
		String line = null;
		while ((line = reader.readLine()) != null) {
			if ((line.trim().startsWith("#") || line.trim().startsWith("!"))
					&& !continueFlg) {
				buf.append(line);
			} else {
				if (line.endsWith("\\")) {
					continueFlg = true;
				} else {
					continueFlg = false;
				}
				buf.append(Encoding.native2ascii(line));
			}
			buf.append("\n");
		}
		if (!fileName.endsWith("\n")) {
			buf.deleteCharAt(buf.length() - 1);
		}
		reader.close();
		return buf.toString();
	}

}
